#!/bin/bash
########################################################################
####  Script Name: sm-lib-kde4-updater
####  version: 0.7.39
####  Date: 2013-11-19

####  Copyright (C) Harald Hope 2011-2013
####  This program is free software; you can redistribute it and/or modify it under
####  the terms of the GNU General Public License as published by the Free Software
####  Foundation; either version 2 of the License, or (at your option) any later version.

####  This program is distributed in the hope that it will be useful, but WITHOUT
####  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
####  FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

####  Get the full text of the GPL here:
####  http://www.gnu.org/licenses/old-licenses/gpl-2.0.html

####  Script Author: Harald Hope
####  This is a library file for smxi and cannot be run independently

####  Script URL: http://smxi.org/sm/sm-lib-kde4-updater
####  Script SVN: http://code.google.com/p/smxi
####  Script Home page: http://techpatterns.com/forums/about736.html
########################################################################

########################################################################
####  FUNCTIONS
########################################################################

###---------------------------------------------------------------------
### primary updating tools
###---------------------------------------------------------------------

kde3_to_kde4_updater_main()
{
	eval $LOGPS
	# get the du data for processing
	local repeat='' options='' opt='' 
	
	print_lib_info $LIB_KDE4_UPDATER
	echo $MLINE
	echo "${S}Beginning the kde 3 to kde 4 conversion process. This is still fresh, be careful."
	echo "Please report, with ${C}$LOG_FILE${S}, any issues to techpatterns.com/smxi forums."
	echo 
	echo "Your user configuration data in ${C}/home/<user>${S} will not be removed when the old KDE packages get"
	echo "removed, and ${C}Kaboom KDE 3 -> 4${S} import tool will import as much as it can to ${C}KDE 4${S} from ${C}KDE 3${S}."
	echo "${C}$SCRIPT_NAME${S} will attempt to reinstall all packages that are installable after the removal."
	echo $LINE

	echo "${C}1 - yes-remove-kde3-install-kde4${S} - Run full conversion to KDE 4, which will remove all of KDE"
	echo "    then try to reinstall any package possible from the list of your current KDE packages."
	echo "${C}2 - no-exit-now${S} - Forget it, going to exit and see what to do."
	echo $LINE
	echo -e $SLE
	echo $LINE
	options="yes-remove-kde3-install-kde4 no-exit-now"
	select opt in $options
	do
		log_function_data "opt selected: $opt"
		case $opt in
			yes-remove-kde3-install-kde4)
				kde3_log_and_removal
				;;
			no-exit-now)
				print_quit
				;;
			*)
				print_error opt
				repeat='true'
				;;
		esac
		break
	done
	
	eval $LOGPE
	if [ "$repeat" == 'true' ];then
		kde3_to_kde4_updater_main
	fi
}
# libk3b-extracodecs arts
kde3_log_and_removal()
{
	eval $LOGUS
	local removedPackages='' cleanedRemovePackages=''  kdeUpgradeInfo='' 
	local package='' packageD='' dpkgCleanKdePackages='' dpkgKdePackagesAll=''
	local extraPackages='' tempName='' package='' lineSize=''
	  
	# note: kipi-plugins, temp possible holds: to be put back in: ktnef kitchensync
	local noUseWildcard='^arts$|artsbuilder|\-data|digikamimageplugins-doc|gwenview-i18n|kaddressbook-plugins|kandy|kate-plugins|kbstate|kcoloredit|kcontrol|kdat|kdebase|kdeeject|kdelib|kdelirc|kdepim-kio-plugins|kdeprint|kdesktop|kde-core|kdict|kdnssd|kdvi|kfax|kfile-plugin|kghostview|khelpcenter$|kicker|kiconedit|kio-apt|kitchensync|kmailcvt|kmenuedit|kmoon|kmrml|knewsticker|knights|kolourpaint$|kooka|korn|kpager|kpersonalizer|kpovmodeler|kpowersave|ksayit|ksmserver|ksplash|ksvg|ksysv|ktip|kuickshow|kview$|kviewshell|kwifimanager|kwin|kworldclock|^lib|\-lib|networkstatus|openoffice.org-kde|quanta|sidux|superkaramba'
	local keepWildCards='kpager'
	
	echo $LINE
	echo "${S}Preparing and procesing your ${C}KDE 3${S} to ${C}KDE 4${S} package data, please wait...${N}"
	
	echo "${S}Calculating and logging installed dpkg kde data (cleaned for processing lists)...${N}"
	dpkgKdePackagesAll="$( dpkg -l | grep -Ei '(kde|konversation)' | awk '$1 ~ /(hi|ii)/ {print $2}'  )"
	# this doesn't get enough of the packages
	# dpkgKdePackagesAll="$( package_tester 'kde' 'wild-full' ) kde-i18n-zhcn"
	
	if [ -n "$( package_tester 'superkaramba' )" ];then
		extraPackages="$extraPackages plasma-scriptengine-superkaramba"
	fi
	if [ -n "$( grep 'libk3b3-extracodecs' <<< $dpkgKdePackagesAll )" ];then
		extraPackages="$extraPackages libk3b3-extracodecs"
	fi
	log_function_data "kde installed dpkg list (all):\n$dpkgKdePackagesAll"
	# now we don't need the linebreaks anymore after this cleaning
	dpkgCleanKdePackages=$( grep -Ev '('$noUseWildcard')' <<< "$dpkgKdePackagesAll" )
	log_function_data "kde installed dpkg list (cleaned):\n$dpkgCleanKdePackages"
	
	echo "${S}Calculating and logging KDE data of packages to be removed (can take a while)...${N}"
	LC_ALL= LC_CTYPE= LC_MESSAGES= LANG= kdeUpgradeInfo="$( echo 'n' | apt-get purge kdelibs kdelibs4c2a kdm 2> /dev/null | sed 's/\*//g' )"
	log_function_data "kde 4 primary initial upgrade apt output:\n$kdeUpgradeInfo"
	
	removedPackages=$( echo "$kdeUpgradeInfo" | gawk '
	BEGIN { IGNORECASE=1 }
	/.*REMOVED:/ {
		# just to make sure no junk gets included, just the raw data
		while ( getline && !/The following|upgraded|installed/ ) {
			print $0
		}
	}
	' )
	log_function_data "kde 4 package remove list:\n$removedPackages"
	
	# construct a master made up of apt-get construct and dpkg installed list
	# to be added later: gtk-qt-engine-kde4 (gtk-qt-engine) skanlite (for kooka)
	for package in $removedPackages $dpkgCleanKdePackages
	do
		# swap known package names
		case $package in
			karm)
				package='ktimetracker'
				;;
			kcoloredit)
				package='kcolorchooser'
				;;
			# this app has a scan tool included so it's fine for now
			kooka|kolourpaint)
				kpackage='kolourpaint4'
				;;
			# this is required for kopete ssl to work
			kopete)
				package='kopete libqca2-plugin-ossl' 
				;;
			kpdf)
				package='okular okular-extra-backends'
				;;
			khelpcenter)
				package='khelpcenter4'
				;;
			# don't run this, will pull in new libreoffice for sid/testing
# 			openoffice.org-kde)
# 				# ooo-gtk conflicts with this package
# 				if [ -z "$( package_tester 'gtk-qt-engine' )" ];then
# 					package='openoffice.org-gtk'
# 				fi
# 				;;
		esac
# 		if [ -n "$( grep -Ev '('$noUseWildcard')' <<< $package )" ];then
		if [ -n "$( grep -Ev '('$noUseWildcard')' <<< $package )" -a *" $package "* != " $cleanedRemovePackages " ];then
			cleanedRemovePackages="$cleanedRemovePackages $package"
		fi
	done 
	cleanedRemovePackages="$cleanedRemovePackages $extraPackages"
	if [ -n "$( grep 'kde-i18n' <<< $cleanedRemovePackages )" ];then
		cleanedRemovePackages=$( sed 's/kde-i18n/kde-l10n/g' <<< "$cleanedRemovePackages" )
	fi
	cleanedRemovePackages="$( sed 's/[[:space:]]/\n/g' <<< $cleanedRemovePackages )"
	cleanedRemovePackages=$( echo -e "$cleanedRemovePackages" | sort -f | uniq )
	cleanedRemovePackages=$( echo $cleanedRemovePackages )
	log_function_data "kde 4 cleaned package remove list:\n$cleanedRemovePackages"
	echo
	echo "${S}Data calculated. The following packages will be reinstalled if possible after"
	echo "the ${C}KDE 3${S} removal and ${C}KDE 4${S} install is completed. Please do not exit this process"
	echo "once it begins or things will get very unpredictable. The next step will remove your"
	echo "installed ${C}KDE 3 / 4${S} completely, then reinstall every package possible."
	echo $LINE
	for package in $cleanedRemovePackages
	do
		if [ "$( wc -c <<< $lineSize )" -lt 70 ];then
			tempName="$tempName$package "
			lineSize="$lineSize$package "
		else
			lineSize=''
			tempName="$tempName$package\n"
		fi
	done
	echo -e "${C}$tempName${N}"
	print_hec
# 	echo "${S}The following is the list of all packages to be removed:${N}"
# 	echo "${C}$removedPackages${N}"
# 	echo "${S}Please exit with ctrl + c now. This data has been logged to ${C}$LOG_FILE${N}"
# 	read fred
	#print_hec
	eval $LOGUE
	
	remove_all_kde "$dpkgKdePackagesAll"
	if [ "$?" -eq 0 ];then
		install_kde4 "$cleanedRemovePackages"
	else
		echo "${E}Error in removing KDE 3. Unknown issue.${N}"
	fi
}

# args: $1 - full kde package list to be removed
remove_all_kde()
{
	eval $LOGUS
	local retValue=0 removeList=$( echo $1 ) # dump line breaks
	local powersaved=''
	
	if [ -n "$( check_package_status 'powersaved' 'i' )" ];then
		powersaved='powersaved'
	fi
	echo $LINE
	if [ -n "$powersaved" ];then
		echo "${S}NOTE: Removing ${C}powersaved${S} to let the native ${C}KDE 4${S} powersave tool ${C}powerdevil${S} work.${N}"
	fi
	echo "${S}Removing all detected ${C}KDE${S} packages prior to reinstallation of ${C}KDE${S} (can take time: please wait)...${N}"
	package_remover "$removeList $powersaved" 'purge' 'group'
	retValue="$?"
	# aptitude is far too unpredictable to try to do any real error handling here, so
	# I'm simply not even going to bother trying since it gives 0 retval for q exit, for example.
	log_function_data "retVal for package removal: $retValue"
	if [ "$retValue" -eq 0 -o "$APT_TYPE" == 'aptitude' ];then
		# clean cruft that will break kdm
		rm -rf /etc/default/kdm.d/* 2>/dev/null
		eval $LOGUE
	else
		eval $LOGUE
		error_handler 'kde4-updater-remove' "$FUNCNAME" "$retValue"
	fi
}

# args: $1 - list of pre-existing kde 3 packages to be replaced
install_kde4()
{
	local package=''
	local installList=$( echo $1 ) # dump line breaks
	
	eval $LOGUS
	echo $LINE
	echo "${S}Beginning ${C}KDE 4${S} install/reinstall/ update process."
	echo "${S}Installing core components of ${C}KDE4${S} now...${N}"
	print_hec
	package_installer "kde-plasma-desktop kdm kaboom plasma-widgets-addons plasma-widgets-workspace" 'install-missing'
	echo $LINE
	echo "${S}Attempting reinstall of your previous KDE packages. This will go through the list created"
	echo "above of ${C}KDE${S} packages to be removed and try to re-install the packages, one by one."
	echo 
	echo "Some packages will require that you say ${C}y/n${S} to the install. This is important because"
	echo "it's too hard to predict individual user systems. Check that a package does not attempt"
	echo "to remove ${C}KDE 4${S} components during this process. If it does, answer ${C}n${S} then"
	echo "let h2 know the package name so that can be fixed.${N}"
	print_hec
	for package in $installList
	do
		echo $LINE
		echo "${S}Testing install status of ${C}$package${S} now...${N}"
		package_installer "$package" 'install-user-ok'
	done
	echo "${S}Done with package install process.${N}"
	eval $LOGUE
	# double check kdm runlevels and fix if required
	kdm_3_to_4_fix_1
	post_kde4_install_fixes
	print_kde4_message
}

post_kde4_install_fixes()
{
	echo $LINE
	echo "${S}Checking post ${C}kde4${S} install and updating anything that needs fixing...${N}"
	# this searches for and deletes: /home/*/.kde/share/config/knemorc
	# presence of this file makes the new knemo taskbar icon not
	# show the the screen icon, presumably due to a changed icon path
	if [ -n "$( ls /home/*/.kde/share/config/knemorc 2>/dev/null )" ];then
		echo "${S}Removing legacy ${C}knemorc${S} files that will not work properly with new version...${N}"
		rm -f /home/*/.kde/share/config/knemorc
	fi
	echo "${S}Post ${C}kde4${S} install check completed...${N}"
}

print_kde4_message()
{
	eval $LOGUS
	local rootHomeData="$( df -h -T | grep -E  '(/|/home)$'  | S=${S} C=${C} awk '{print $7, ENVIRON["S"]" - ", "Type:"ENVIRON["C"], $2, ENVIRON["S"]"Size:"ENVIRON["C"], $3, ENVIRON["S"]"Used:"ENVIRON["C"], $4, ENVIRON["S"]"("ENVIRON["C"], $6, ENVIRON["S"]")", "Free:"ENVIRON["C"], $5}' )"
	
	echo $LINE
	echo "${S}Please note: the first time each user logs-in to their new ${C}KDE 4${S} desktop,"
	echo "the ${C}Kaboom${S} program will run. I recommend the following options:"
	echo "${M}(*) Use current KDE 3 settings as initial for KDE 4 (standard)"
	echo "${M}[x] Backup existing KDE 3 settings (highly recommended)"
	echo "${S}Please note that if you had a lot of data in kmail or other places in your settings .xxx files,"
	echo "you may want to make sure you have enough space before proceeding. Kaboom will print"
	echo "how much room the backup needs: eg: ${M}Backup needs 205kB free disk space"
	
	echo $LINE
	echo "${S}Here is your current diskspace for ${C}/${S} (and ${C}/home${S} if separate)"
	echo "${C}$rootHomeData"
	echo $LINE
	echo "${S}If the system feels slow or sluggish after the desktop starts, try disabling"
	echo "${C}Effects${S} in ${C}System Settings${S} (${M}K-Menu -> Computer -> System Settings${S})"
	echo 
	echo "${S}Ok, good luck, I hope this works for you. Remember, you'll have to redo your desktop a bit,"
	echo "since only the KDE stuff like Kmail, KDE sessions, etc, will transfer to KDE 4.${N}"
	print_hec
	eval $LOGUE
}

###**EOF**###
